﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Renci.Ogc.WebService.Common;

namespace Renci.Ogc.WebService.Sos
{
    public class SosUrnResolver : BaseUrnResolver
    {
        private static string _version = "1.0.0";

        public SosUrnResolver(BaseOperation operation)
            : base(operation)
        {

        }

        /// <summary>
        /// Specifies regular expression to parse URN string
        /// </summary>
        private static Regex _reUrn = new Regex(@"^urn:renci:sdb:swe:(?<name>[^:]+):(?<version>\d{1,2}[.]\d\d?([.]\d)?):(?<value>[^:]+)$", RegexOptions.Compiled);

        /// <summary>
        /// Gets the value from OGC urn string.
        /// </summary>
        /// <param name="urn"></param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public override NameValue GetUrnNameValue(string urn)
        {
            Match match = _reUrn.Match(urn);

            if (!match.Success)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid urn string.", urn));
            }

            string urnName = match.Result("${name}");
            string urnVersion = match.Result("${version}");
            string urnValue = match.Result("${value}");

            if (urnVersion.Equals(_version))
            {
                return new NameValue
                    {
                        Name = urnName,
                        Value = urnValue,
                    };
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// Gets OGC compliant urn string for specific defintion and name
        /// </summary>
        /// <param name="name">Name</param>
        /// <param name="value"></param>
        /// <returns>OGC compliant urn string</returns>
        protected override string GetUrnString(string name, string value)
        {
            return string.Format(CultureInfo.InvariantCulture, "urn:renci:sdb:swe:{0}:{1}:{2}", name, _version, value);
        }
    }
}
